// http://stackoverflow.com/questions/3414438/java-resume-download-in-urlconnection

import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Download {
    static Path getPartialFilePath(Path destPath) {
        return Paths.get(destPath.toString()+".part");
    }

    static void perform(URL url, Path destPath) {
        Path partialDestPath=getPartialFilePath(destPath);
        try {
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            long position=0;
            String action="downloading";
            File partialDestFile=partialDestPath.toFile();
            if (partialDestFile.exists()) {
                position=partialDestFile.length();
                if (position>0) {
                    connection.setDoOutput(true);
                    connection.setRequestProperty("Range", "bytes="+position+"-");
                    action="resuming";
                }
            }
            System.out.format("  %s \"%s\"",action,destPath.getFileName()).println();
            connection.connect();
            if (connection.getResponseCode()!=416) {
                ReadableByteChannel rbc=Channels.newChannel(connection.getInputStream());
                FileOutputStream fos = new FileOutputStream(partialDestFile,true);
                fos.getChannel().transferFrom(rbc,position,Long.MAX_VALUE);
                fos.close();
                rbc.close();
            }
            Files.move(partialDestPath,destPath,StandardCopyOption.REPLACE_EXISTING);
        }
        catch(Exception e) {
            System.err.println(e.getMessage());
        }
    }
}
